package com.design.graduation.asdemo.controller;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.bumptech.glide.Glide;
import com.design.graduation.asdemo.Constant;
import com.design.graduation.asdemo.R;
import com.design.graduation.asdemo.base.ActionBarActivity;
import com.design.graduation.asdemo.event.BusProvider;
import com.design.graduation.asdemo.event.PositionInfo;
import com.design.graduation.asdemo.manager.QiniuManager;
import com.design.graduation.asdemo.manager.UserManager;
import com.design.graduation.asdemo.model.DetailsInfo;
import com.design.graduation.asdemo.model.InfoEntity;
import com.design.graduation.asdemo.network.model.LoginResult;
import com.design.graduation.asdemo.network.model.TokenResult;
import com.design.graduation.asdemo.network.service.HttpObserver;
import com.design.graduation.asdemo.utils.GeoHashKit;
import com.design.graduation.asdemo.utils.ImageUtils;
import com.design.graduation.asdemo.utils.JSONUtil;
import com.design.graduation.asdemo.utils.ToastUtil;
import com.design.graduation.asdemo.view.EditDialog;
import com.design.graduation.asdemo.view.adapter.BaseRecyclerAdapter;
import com.design.graduation.asdemo.view.adapter.RecyclerViewHolder;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.squareup.otto.Subscribe;
import com.yongchun.library.view.ImageSelectorActivity;

import org.joda.time.DateTime;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by lijinyuan on 16/2/27.
 */

public class WriteDetailsActivity extends ActionBarActivity {
    private MapView mapView;
    private AMap aMap;
    private static final int REQUEST_IMAGE = 1001;
    private EditDialog editDialog;
    private List<String> imgList;
    private BaseRecyclerAdapter<String> adapter;
    private DetailsInfo detailsInfo;
    private List<String> uploadList;

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.img_title_content)
    TextView imgTitleContent;
    @Bind(R.id.details_push_img)
    LinearLayout detailsPushImg;
    @Bind(R.id.shrink_img)
    ImageView shrinkImg;
    @Bind(R.id.img_title)
    RelativeLayout imgTitle;
    @Bind(R.id.details_img)
    RecyclerView detailsImg;
    @Bind(R.id.content_map_title)
    TextView contentMapTitle;
    @Bind(R.id.shrink_position)
    ImageView shrinkPosition;
    @Bind(R.id.position_title)
    RelativeLayout positionTitle;
    @Bind(R.id.content_map)
    MapView contentMap;
    @Bind(R.id.details_price_title)
    TextView detailsPriceTitle;
    @Bind(R.id.details_price)
    EditText detailsPrice;
    @Bind(R.id.details_edit_complete)
    Button detailsEditComplete;
    @Bind(R.id.details_price_re)
    RelativeLayout detailsPriceRe;
    @Bind(R.id.details_phone_title)
    TextView detailsPhoneTitle;
    @Bind(R.id.details_phone)
    EditText detailsPhone;
    @Bind(R.id.details_phone_complete)
    Button detailsPhoneComplete;
    @Bind(R.id.details_Input_phone)
    TextInputLayout detailsInputPhone;
    @Bind(R.id.details_describe_title)
    TextView detailsDescribeTitle;
    @Bind(R.id.details_describe)
    TextView detailsDescribe;
    @Bind(R.id.write_content)
    LinearLayout writeContent;

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null && outState != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_details);
        ButterKnife.bind(this);
        BusProvider.register(this);
        imgList = new ArrayList<>();
        uploadList=new ArrayList<>();
        detailsInfo = new DetailsInfo();
        mapView = (MapView) findViewById(R.id.content_map);
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        init();

    }

    public void init() {

        setToolBar();
        setInput();
        setMap();
    }


    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        BusProvider.unregister(this);
    }


    private void setMap() {
        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setScaleControlsEnabled(false);//比例尺
        uiSettings.setMyLocationButtonEnabled(true);//定位图标
        uiSettings.setZoomControlsEnabled(false);//显示缩放
        uiSettings.setRotateGesturesEnabled(false);//手势旋转
        uiSettings.setScrollGesturesEnabled(false);//手势移动
        uiSettings.setZoomGesturesEnabled(false);//手势缩放
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.setTiltGesturesEnabled(false);
        uiSettings.isMyLocationButtonEnabled();
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        CameraUpdate cu = CameraUpdateFactory.zoomTo(14);//只所放到16级别 其他参数不
    }


    public void toChooseImg(View view) {

        ImageSelectorActivity.start(WriteDetailsActivity.this, 5, ImageSelectorActivity.MODE_MULTIPLE, true, true, false, REQUEST_IMAGE);

        adapter = new BaseRecyclerAdapter<String>(WriteDetailsActivity.this, imgList) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.item_recycler_image;
            }

            @Override
            public void bindData(RecyclerViewHolder holder, int position, String item) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(item)) {
                    Glide.with(WriteDetailsActivity.this).load(item).into(holder.getImageView(R.id.recycler_image));
                }
            }


        };

        detailsImg.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        detailsImg.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing MediaImage
        imgList.clear();
        if (resultCode == RESULT_OK) {
            ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
            for (String imageUrl : images) {
                imgList.add(imageUrl);
            }

            Observable.from(imgList).map(new Func1<String, File>() {
                @Override
                public File call(String url) {
                    return ImageUtils.getSmallBitmap(WriteDetailsActivity.this, url, "IMG");
                }
            }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Observer<File>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                }

                @Override
                public void onNext(File file) {
                    QiniuManager.uploadFile("11111111111", file, file.getName(), new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {
                            String url = Constant.kQiNiuDomain + key + "?" + DateTime.now().getMillis();
                            uploadList.add(url);//
                        }
                    });

                }
            });


            String imageListJson = JSON.toJSONString(imgList);
            detailsInfo.setImgUrl(imageListJson);
            adapter.notifyDataSetChanged();
        }
    }

    public void toPosition(View view) {
        startActivity(new Intent(WriteDetailsActivity.this, LocationActivity.class));
    }

    @Subscribe
    public void getPosition(PositionInfo position) {
        setMap(position);
        contentMapTitle.setText(position.getEntity().getAddress().toString());
        detailsInfo.setLat(String.valueOf(position.getEntity().getLat()));
        detailsInfo.setLon(String.valueOf(position.getEntity().getLon()));
        detailsInfo.setPosition(position.getEntity().getAddress());

    }

    private void setMap(PositionInfo positionInfo) {
        InfoEntity last = null;
        MyLocationStyle locationStyle = new MyLocationStyle();
        locationStyle.strokeColor(Color.BLUE);
        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setScaleControlsEnabled(false);//比例尺
        uiSettings.setMyLocationButtonEnabled(true);//定位图标
        uiSettings.setZoomControlsEnabled(false);//显示缩放
        uiSettings.setRotateGesturesEnabled(false);//手势旋转
        uiSettings.setScrollGesturesEnabled(false);//手势移动
        uiSettings.setZoomGesturesEnabled(false);//手势缩放
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.isMyLocationButtonEnabled();
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

        CameraUpdate cu = CameraUpdateFactory.zoomTo(14);//只所放到16级别 其他参数不变
        aMap.moveCamera(cu);//通过移动相机更改地图缩放级别

        last = new InfoEntity(positionInfo.getEntity().getLon(), positionInfo.getEntity().getLat(), positionInfo.getEntity().getAddress());
        animateCamera(last.getLon(), last.getLat(), 14);
    }

    private void animateCamera(double lon, double lat, float scale) {
        if (aMap != null) {
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(lat, lon), scale));
        }
    }


    @OnClick(R.id.details_describe)
    public void setInput() {
        detailsDescribe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editDialog == null) {
                    editDialog = new EditDialog(v.getContext(), new EditDialog.EnsureOrCancelListener() {
                        @Override
                        public void onEnsureClicked() {
                            detailsDescribe.setText(editDialog.getEditText().getText().toString());
                            detailsInfo.setContent(editDialog.getEditText().getText().toString());
                        }

                        @Override
                        public void onCancelClicked() {
                            editDialog.dismiss();
                        }
                    }, "请输入您要出租房屋的详细描述");
                }
                editDialog.show();
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem item = menu.findItem(R.id.action_text);
//        MenuItem item1 = menu.findItem(R.id.action_img);
        item.setVisible(false);
        return true;
    }

    private void setToolBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("编辑房屋信息");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.icon_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_img:
                        sendMessage();
                        break;
                    case R.id.action_text:
                        finish();
                }
                return true;
            }
        });

    }

    private void sendMessage() {
        if (isComplete() == true) {
            GeoHashKit hashKit = new GeoHashKit();
            String hash = hashKit.encode(Double.valueOf(detailsInfo.getLat()), Double.valueOf(detailsInfo.getLon()));
            UserManager.setRoomMessage(
                    detailsInfo.getPosition(), detailsInfo.getLon() + "", detailsInfo.getLat() + "", detailsInfo.getNumber(), detailsInfo.getContent(), detailsInfo.getPhone(), JSONUtil.toJSONString(uploadList)
                    , hash, new Observer<LoginResult>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onNext(LoginResult stringResult) {
                            if (stringResult.getStatus() == 200) {
                                ToastUtil.showLongToast(stringResult.getMessage());
                                finish();

                            }
                        }
                    });
        }

    }

    private Boolean isComplete() {

        detailsInfo.setPhone(detailsPhone.getText().toString().trim());
        detailsInfo.setNumber(detailsPrice.getText().toString());//隐藏键盘

        if (detailsInfo.getImgUrl() == null) {
            ToastUtil.showShortToast("请上传图片");
            return false;
        }
        if (detailsInfo.getPosition() == null) {
            ToastUtil.showShortToast("请输入位置");
            return false;
        }
        if (detailsInfo.getNumber().toString().length() == 0) {
            ToastUtil.showShortToast("请输入价格");
            return false;
        }
        if (detailsInfo.getPhone().toString().length() != 11) {
            ToastUtil.showShortToast("请对输入正确联系电话");
            return false;
        }
        if (detailsInfo.getContent() == null) {
            ToastUtil.showShortToast("请对房屋进行详细描述");
            return false;
        }

        return true;
    }


}


